package com.woniuxy.consumeserver.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.consumeserver.pojo.FinanceConsume;
import com.woniuxy.consumeserver.pojo.FinancePayPlan;
import com.woniuxy.consumeserver.service.FinanceConsumeService;
import com.woniuxy.consumeserver.mapper.FinanceConsumeMapper;
import com.woniuxy.consumeserver.service.FinancePayPlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
* @author 76169
* @description 针对表【finance_consume】的数据库操作Service实现
* @createDate 2024-12-17 19:05:02
*/
@Slf4j
@Service
public class FinanceConsumeServiceImpl extends ServiceImpl<FinanceConsumeMapper, FinanceConsume>
    implements FinanceConsumeService{
    @Autowired
    private FinancePayPlanService financePayPlanService;

    @Override
    public Boolean payPlan(Long userId, Long orderId, BigDecimal amount) {
        //默认情况：用户已开户
        // 判断用户的金额（用户总金额>=用户已用金额+本次购买金额）是否足够
        FinanceConsume consume = lambdaQuery().eq(FinanceConsume::getFinanceUserId, userId).one();
        BigDecimal financeAmount = consume.getFinanceAmount();
        BigDecimal financeUsedQuota = consume.getFinanceUsedQuota();
        int i = financeAmount.compareTo(financeUsedQuota.add(amount));
        if(i<0){
            log.error("用户余额不足,用户总金额:{},用户已用金额:{},本次购买金额:{}",financeAmount,financeUsedQuota,amount);
            return false;
        }
        //修改用户已用金额
        consume.setFinanceUsedQuota(financeUsedQuota.add(amount));
        updateById(consume);
        return payPlan(consume,orderId,amount);
    }

    /**
     *
     * @param consume
     * @param amount
     * @return
     */
    private Boolean payPlan(FinanceConsume consume,Long orderId, BigDecimal amount){
        //每期还款金额=（购买金额+利息）/12
        BigDecimal payPlanAmount = amount.multiply(new BigDecimal(1.1)).divide(new BigDecimal(12), BigDecimal.ROUND_HALF_UP);

        // 设置每期还款的截止日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());//设置当前时间
        calendar.set(Calendar.DAY_OF_MONTH,10);//还款的截止日期每个月10号

        // 保存分期数据
        List<FinancePayPlan> list=new ArrayList<>(12);
        FinancePayPlan financePayPlan=null;
        for (int i=0;i<12;i++){
            //还款的截止日期为下个月
            calendar.add(Calendar.MONTH,1);

            financePayPlan = new FinancePayPlan();
            financePayPlan.setFinanceConsumeId(consume.getId());
            financePayPlan.setFinanceOrderId(orderId);
            financePayPlan.setPayAmount(payPlanAmount);
            financePayPlan.setPayPlanTime(calendar.getTime());
            list.add(financePayPlan);
        }
        return financePayPlanService.saveBatch(list);
    }
}




